package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.discover.Maori_Discover_Word_Details;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.model.Maori_NavDrawerItem;
import com.maori.languageapp.service.Maori_Loading_Splash;
import com.maori.languageapp.subview.Maori_BookMark_Items;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_MainActivity extends FragmentActivity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;
	TextView profile_text;
	String SYNCACTIVE = "0";

	ProgressDialog mProgressDialog;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String mainUrl;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	JSONArray jArray;
	private SQLiteDatabase mydb;
	String UserArray, LanguageArray, CategoryArray, DialectArray, MediaArray,
			ContentTypeArray, WordsArray;

	String LastDownloadUpdateTime = "2014-01-01 12:00:00";
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";
	private String IDIOM_TABLE = "Idiom";

	String UID;

	private Dialog mSplashDialog;;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			SYNCACTIVE = extras.getString("SYNC");
			if (SYNCACTIVE.equals("ACTIVE")) {
				new DownloadLanguageDetails().execute();
			}
		}

		mTitle = mDrawerTitle = getTitle();

		navMenuTitles = getResources().getStringArray(
				R.array.maori_nav_drawer_items);

		navMenuIcons = getResources().obtainTypedArray(
				R.array.maori_nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
		profile_text = (TextView) findViewById(R.id.profile_text);
		// PSJ - Adding Profile Picture
		View header = getLayoutInflater().inflate(
				R.layout.maori_profile_header, null);
		mDrawerList.addHeaderView(header);
		//
		// profile_text.setText("Eranda");
		navDrawerItems = new ArrayList<Maori_NavDrawerItem>();

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[0],
				navMenuIcons.getResourceId(0, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[1],
				navMenuIcons.getResourceId(1, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[2],
				navMenuIcons.getResourceId(2, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[3],
				navMenuIcons.getResourceId(3, -1), true, "22"));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[4],
				navMenuIcons.getResourceId(4, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[5],
				navMenuIcons.getResourceId(5, -1), true, "50+"));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[6],
				navMenuIcons.getResourceId(6, -1)));

		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		adapter = new Maori_NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#0d284c")));

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menubutton, R.string.app_name, R.string.app_name) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			displayView(0);
		}
	}

	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 1:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 2:
			fragment = new Maori_Main_Fragment(1);
			break;
		case 3:
			fragment = new Maori_Main_Fragment(2);
			break;
		case 4:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 5:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 6:
			//fragment = new Maori_Main_Fragment(0);
			Intent myIntent = new Intent(Maori_MainActivity.this,
					Maori_BookMark_Items.class);
			myIntent.putExtra("CATEGORY","word");
			myIntent.putExtra("BMNID","100");
			startActivity(myIntent);
			break;
		case 7:
			fragment = new Maori_Main_Fragment(8);
			break;

		default:
			break;
		}

		if (fragment != null) {

			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);

		} else {
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	// Download available details
	private class DownloadLanguageDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_MainActivity.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Downloading....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			// *****Download and Update Language Details*****
			ArrayList<NameValuePair> nameValuePairsLanguage = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.LanguageURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsLanguage));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				LanguageArray = sb.toString();

				jArray = new JSONArray(LanguageArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String LID = json_data.getString("LID");
					String Language = json_data.getString("Language");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(LANGUAGE_TABLE, null,
								"LID ='" + LID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Language");
						} else {
							enterLanguageInfo.put("LID", LID.trim());
							enterLanguageInfo.put("Language", Language.trim());
							mydb.insert(LANGUAGE_TABLE, null, enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Language Download Complete------

			// *****Download and Update Category Details*****
			ArrayList<NameValuePair> nameValuePairsCategory = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.CategoryURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsCategory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				CategoryArray = sb.toString();

				jArray = new JSONArray(CategoryArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String node_category = json_data.getString("node_category");
					String NCMID = json_data.getString("NCMID");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(NODECATEGORY_TABLE,
								null, "NCMID ='" + NCMID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Category");
						} else {
							enterLanguageInfo.put("node_cat_id", NCMID.trim());
							enterLanguageInfo.put("node_category",
									node_category.trim());
							enterLanguageInfo.put("NCMID", NCMID.trim());
							mydb.insert(NODECATEGORY_TABLE, null,
									enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Category Download Complete------

			// *****Download and Update Dialect Details*****
			ArrayList<NameValuePair> nameValuePairsDialect = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.DialectURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsDialect));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				DialectArray = sb.toString();

				jArray = new JSONArray(DialectArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String dialact_id = json_data.getString("dialact_id");
					String dialact = json_data.getString("dialact");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterDialectInfo = new ContentValues();
					// Check Previous Language
					Cursor readDialectDetails = null;
					try {
						readDialectDetails = mydb.query(DIALACT_TABLE, null,
								"dialact_id ='" + dialact_id.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (readDialectDetails != null) {
						if (readDialectDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Dialect");
						} else {
							enterDialectInfo.put("dialact_id",
									dialact_id.trim());
							enterDialectInfo.put("dialact", dialact.trim());
							mydb.insert(DIALACT_TABLE, null, enterDialectInfo);
							readDialectDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Dialect Download Complete------

			// *****Download and Update Media Details*****
			ArrayList<NameValuePair> nameValuePairsMedia = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.MediaURL);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsMedia));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				MediaArray = sb.toString();

				jArray = new JSONArray(MediaArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String MID = json_data.getString("MID");
					String media_type = json_data.getString("media_type");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterMediaInfo = new ContentValues();
					// Check Previous Language
					Cursor readMediaDetails = null;
					try {
						readMediaDetails = mydb.query(MEDIA_TABLE, null,
								"MID ='" + MID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readMediaDetails != null) {
						if (readMediaDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Media");
						} else {
							enterMediaInfo.put("MID", MID.trim());
							enterMediaInfo.put("media_type", media_type.trim());
							mydb.insert(MEDIA_TABLE, null, enterMediaInfo);
							readMediaDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Dialect Download Complete------

			// *****Download and Update Content Type Details*****
			ArrayList<NameValuePair> nameValuePairsContentType = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.ContentTypeURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsContentType));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				ContentTypeArray = sb.toString();

				jArray = new JSONArray(ContentTypeArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String content_type_id = json_data
							.getString("content_type_id");
					String content = json_data.getString("content");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterContentTypeInfo = new ContentValues();
					// Check Previous Language
					Cursor readContentTypeDetails = null;
					try {
						readContentTypeDetails = mydb.query(CONTENTTYPE_TABLE,
								null,
								"content_type_id ='" + content_type_id.trim()
										+ "'", null, null, null, null);
					} catch (Exception e) {
					}
					if (readContentTypeDetails != null) {
						if (readContentTypeDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Content Type");
						} else {
							enterContentTypeInfo.put("content_type_id",
									content_type_id.trim());
							enterContentTypeInfo.put("content", content.trim());
							mydb.insert(CONTENTTYPE_TABLE, null,
									enterContentTypeInfo);
							readContentTypeDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Content Type Download Complete------

			// *****Download and Update Words Details*****

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.WordsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE WORDS :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String WordID = json_data.getString("WordID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String word = json_data.getString("word");
					String otherwords = json_data.getString("otherwords");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(WORD_TABLE, null,
								"WordID ='" + WordID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("WordID", WordID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("word", word.trim());
							wordsUpdate.put("otherwords", otherwords.trim());
							mydb.update(WORD_TABLE, wordsUpdate, "WordID ='"
									+ WordID.trim() + "'", null);
						} else {
							enterWordInfo.put("WordID", WordID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("word", word.trim());
							enterWordInfo.put("Otherwords", otherwords.trim());
							mydb.insert(WORD_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Idiom Details*****

			ArrayList<NameValuePair> nameValuePairsIdiom = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.IdiomURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST IDIOM :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsIdiom));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();

				Log.e("RESPONSE Idiom :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String IdiomID = json_data.getString("IdiomID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String Idiom = json_data.getString("Idiom");
					String Otheridioms = json_data.getString("Otheridioms");
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(IDIOM_TABLE, null,
								"IdiomID ='" + IdiomID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("IdiomID", IdiomID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Idiom", Idiom.trim());
							wordsUpdate.put("Otheridioms", Otheridioms.trim());

							mydb.update(IDIOM_TABLE, wordsUpdate, "WordID ='"
									+ IdiomID.trim() + "'", null);
						} else {
							enterWordInfo.put("IdiomID", IdiomID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Idiom", Idiom.trim());
							enterWordInfo
									.put("Otheridioms", Otheridioms.trim());
							mydb.insert(IDIOM_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Songs Details*****

			ArrayList<NameValuePair> nameValuePairsSongs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.SongsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST SONGS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsSongs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Songs :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String SongID = json_data.getString("SongID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String song_title = json_data.getString("song_title");
					String song_content = json_data.getString("song_content");
					String other_song_title = json_data
							.getString("other_song_title");
					String other_song_content = json_data
							.getString("other_song_content");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(SONG_TABLE, null,
								"SongID ='" + SongID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Song");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("SongID", SongID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("song_title", song_title.trim());
							wordsUpdate
									.put("song_content", song_content.trim());
							wordsUpdate.put("other_song_title",
									other_song_title.trim());
							wordsUpdate.put("other_song_content",
									other_song_content.trim());
							mydb.update(SONG_TABLE, wordsUpdate, "SongID ='"
									+ SongID.trim() + "'", null);
						} else {
							enterWordInfo.put("SongID", SongID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("song_title", song_title.trim());
							enterWordInfo.put("song_content",
									song_content.trim());
							enterWordInfo.put("other_song_title",
									other_song_title.trim());
							enterWordInfo.put("other_song_content",
									other_song_content.trim());
							mydb.insert(SONG_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Phrase Details*****

			ArrayList<NameValuePair> nameValuePairsPhrase = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.PhraseURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsPhrase));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Phrase :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String PhraseID = json_data.getString("PhraseID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String Phrase = json_data.getString("Phrase");
					String OtherPhrase = json_data.getString("OtherPhrase");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(PHRASE_TABLE, null,
								"PhraseID ='" + PhraseID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Phrase");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("PhraseID", PhraseID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Phrase", Phrase.trim());
							wordsUpdate.put("OtherPhrase", OtherPhrase.trim());

							mydb.update(PHRASE_TABLE, wordsUpdate,
									"PhraseID ='" + PhraseID.trim() + "'", null);
						} else {
							enterWordInfo.put("PhraseID", PhraseID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Phrase", Phrase.trim());
							enterWordInfo
									.put("OtherPhrase", OtherPhrase.trim());
							mydb.insert(PHRASE_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Story Details*****

			ArrayList<NameValuePair> nameValuePairsStory = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.StoryURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsStory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE STORY :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String StoryID = json_data.getString("StoryID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String story_title = json_data.getString("story_title");
					String story_content = json_data.getString("story_content");
					String other_story_title = json_data
							.getString("other_story_title");
					String other_story_content = json_data
							.getString("other_story_content");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(STORY_TABLE, null,
								"StoryID ='" + StoryID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting StoryID");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("StoryID", StoryID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("story_title", story_title.trim());
							wordsUpdate.put("story_content",
									story_content.trim());
							wordsUpdate.put("other_story_title",
									other_story_title.trim());
							wordsUpdate.put("other_story_content",
									other_story_content.trim());
							mydb.update(STORY_TABLE, wordsUpdate, "StoryID ='"
									+ StoryID.trim() + "'", null);
						} else {
							enterWordInfo.put("StoryID", StoryID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo
									.put("story_title", story_title.trim());
							enterWordInfo.put("story_content",
									story_content.trim());
							enterWordInfo.put("other_story_title",
									other_story_title.trim());
							enterWordInfo.put("other_story_content",
									other_story_content.trim());
							mydb.insert(STORY_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
		}

	}
	
	
	public void onBackPressed() {
		super.onBackPressed();
		displayCancelDialog();
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Maori_MainActivity.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_UserLoginActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		builder.show();
	}
	
	//***********Memory Handling****************
	@Override
	   protected void onStop(){
	      super.onStop();
	   }

	   //Fires after the OnStop() state
	   @Override
	   protected void onDestroy() {
	      super.onDestroy();
	      try {
	         trimCache(this);
	      } catch (Exception e) {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }

	   public static void trimCache(Context context) {
	      try {
	         File dir = context.getCacheDir();
	         if (dir != null && dir.isDirectory()) {
	            deleteDir(dir);
	         }
	      } catch (Exception e) {
	         // TODO: handle exception
	      }
	   }

	   public static boolean deleteDir(File dir) {
	      if (dir != null && dir.isDirectory()) {
	         String[] children = dir.list();
	         for (int i = 0; i < children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	               return false;
	            }
	         }
	      }

	      // The directory is now empty so delete it
	      return dir.delete();
	   }

}
